#include "StdAfx.h"
#include "polygon_2.h"
#include "boost\foreach.hpp"


polygon_2::polygon_2(void)
{
}


polygon_2::~polygon_2(void)
{
}

box_2 polygon_2::bounds(void) const
{
  double left    = std::numeric_limits<double>::max();
  double right   = std::numeric_limits<double>::min();
  double top     = std::numeric_limits<double>::max();
  double bottom  = std::numeric_limits<double>::min();

  BOOST_FOREACH(const point_2& vertex, *this)
  {
    left    = std::min(left,    vertex.x);
    right   = std::max(right,   vertex.x);
    top     = std::min(top,     vertex.y);
    bottom  = std::max(bottom,  vertex.y);
  }

  return box_2(left, top, right, bottom);
}

bool polygon_2::within(const point_2& pt) const
{
  int wn    = 0;
  int nvert = num_points();

  // loop through all edges of the polygon
  for(int i=0, j=nvert-1; i<nvert; j=i++) { // Edge from vertexes[j] to vertexes[i]
    if((*this)[j].y<=pt.y) {
      if((*this)[i].y>pt.y && pt.left((*this)[j], (*this)[i])) { ++wn; }
    } else {
      if(!((*this)[i].y>pt.y) && pt.right((*this)[j], (*this)[i])) { --wn; }
    }
  }

  return wn!=0;
}

bool polygon_2::intersects(const box_2& box) const
{
  BOOST_FOREACH(const point_2& vertex, *this)
  {
    if (box.within(vertex)) {
      return true;
    }
  }

  return false;
}
